import os
import win32file
import win32con
from threading import Thread

class FileListener(Thread):
    def __init__(self, fileSynchronizer):
        Thread.__init__(self)
        self._fileSynchronizer = fileSynchronizer

class Win32FileListener(FileListener):
    '''Copy pasted from http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
    '''
    def __init__(self, fileSynchronizer, config):
        FileListener.__init__(self, fileSynchronizer)
        self._path_to_watch = config.get('localfolder')
        if not os.path.exists(self._path_to_watch):
            raise Exception('folder ' + self._path_to_watch + ' does not exist')
    
    def run(self):
        self._fileSynchronizer.start()
        hDir = win32file.CreateFile(
          self._path_to_watch,
          0x0001,
          win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
          None,
          win32con.OPEN_EXISTING,
          win32con.FILE_FLAG_BACKUP_SEMANTICS,
          None
        )
        while 1:
            #pass
            results = win32file.ReadDirectoryChangesW(
                hDir,
                1024,
                True,
                win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
                 win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
                 win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
                 win32con.FILE_NOTIFY_CHANGE_SIZE |
                 win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
                 win32con.FILE_NOTIFY_CHANGE_SECURITY,
                None,
                None
            )
            for action, file in results:
                full_filename = os.path.join(self._path_to_watch, file)
                self._fileSynchronizer.add_file(full_filename, action)